public class Exist {
    // leetcode 单词搜索
    // https://leetcode.cn/problems/word-search/description/?envType=study-plan-v2&envId=top-100-liked
    boolean[][] vis;
    int[] x = {0,0,-1,1};
    int[] y = {-1,1,0,0};
    public boolean exist(char[][] board, String word) {
        int n1 = board.length, n2 = board[0].length;
        vis = new boolean[n1][n2];
        for (int i = 0; i < n1; i++) {
            for (int j = 0; j < n2; j++) {
                if (board[i][j] == word.charAt(0)) {
                    vis[i][j] = true;
                    boolean result = backTracing(board, word, i, j, 1);
                    vis[i][j] = false;
                    if (result) return true;
                }
            }
        }
        return false;
    }

    private boolean backTracing(char[][] board, String word, int row, int col, int index) {
        if (index >= word.length()) {
            return true;
        }
        for (int i = 0; i < 4; i++) {
            int newRow = row + x[i];
            int newCol = col + y[i];
            if (newRow >= 0 && newRow < board.length && newCol >= 0 && newCol < board[0].length && !vis[newRow][newCol] && board[newRow][newCol] == word.charAt(index)) {
                vis[newRow][newCol] = true;
                if (backTracing(board, word, newRow, newCol, index+1)) return true;
                vis[newRow][newCol] = false;
            }
        }
        return false;
    }
}
